package com.clothing.customization.controller;

import com.clothing.customization.common.ApiResponse;
import com.clothing.customization.entity.ImageFile;
import com.clothing.customization.service.ImageFileService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletRequest;

/**
 * 设计师订单控制器
 */
@RestController
@RequestMapping("/designer/order")
@RequiredArgsConstructor
@CrossOrigin(origins = "*", allowedHeaders = "*", exposedHeaders = "*", methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.DELETE, RequestMethod.OPTIONS})
@Slf4j
public class DesignerOrderController {

    private final ImageFileService imageFileService;
    
    /**
     * 订单图片上传
     *
     * @param file 上传的文件
     * @param orderNo 订单编号
     * @param imageType 图片类型
     * @param description 描述
     * @return 图片访问URL
     */
    @PostMapping("/upload")
    public ApiResponse<String> uploadOrderImage(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "orderNo", required = false) String orderNo,
            @RequestParam(value = "imageType", required = false, defaultValue = "design") String imageType,
            @RequestParam(value = "description", required = false) String description,
            HttpServletRequest request) {
        
        log.info("==== 订单图片上传接口被调用 ====");
        log.info("接收到订单图片上传请求: filename={}, contentType={}, size={}, orderNo={}, imageType={}", 
                file.getOriginalFilename(), file.getContentType(), file.getSize(), orderNo, imageType);
        log.info("请求来源: {}", request.getRemoteAddr());
        
        if (file.isEmpty()) {
            return ApiResponse.error("上传失败，请选择文件");
        }
        
        // 验证文件类型
        String contentType = file.getContentType();
        if (contentType == null || !contentType.startsWith("image/")) {
            return ApiResponse.error("只允许上传图片文件");
        }
        
        try {
            // 构建模块名称，例如 orderImage_design
            String module = "orderImage_" + imageType;
            // 将订单编号转换为数值ID，简单示例
            Long relationId = orderNo != null ? Math.abs(orderNo.hashCode()) % 1000000L : 0L;
            
            // 上传文件并保存元数据
            ImageFile imageFile = imageFileService.uploadImage(file, module, relationId);
            
            // 返回文件访问URL
            log.info("订单图片上传成功: {}", imageFile.getAccessUrl());
            return ApiResponse.success(imageFile.getAccessUrl());
        } catch (Exception e) {
            log.error("订单图片上传失败", e);
            return ApiResponse.error("文件上传失败: " + e.getMessage());
        }
    }
} 